package com.briup.test2;

/**
 * @date 2025/10/23 11:45
 * 多线程交替输出0和1
 * （synchronized + wait/notify 方式实现）
 */
public class AlternatePrint {
    private int flag = 0;
    private final Object lock = new Object();

    public static void main(String[] args) {
        AlternatePrint ap = new AlternatePrint();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                synchronized (ap.lock) {
                    while (ap.flag != 0) {
                        try { ap.lock.wait(); } catch (InterruptedException e) {}
                    }
                    System.out.print(0+" ");
                    ap.flag = 1;
                    ap.lock.notify();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                synchronized (ap.lock) {
                    while (ap.flag != 1) {
                        try { ap.lock.wait(); } catch (InterruptedException e) {}
                    }
                    System.out.print(1+" ");
                    ap.flag = 0;
                    ap.lock.notify();
                }
            }
        }).start();
    }
}
